package com.zyw.teacher.login.service.impl;

import com.zyw.teacher.login.entity.Role;
import com.zyw.teacher.login.entity.User;
import com.zyw.teacher.login.mapper.UserMapper;
import com.zyw.teacher.login.mapper.UserRoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Description: 授权扩展点
 * @Author: zyw
 * @Date: 2018/12/13
 */
public class DataBaseManagerToken implements AuthenticationManager {

    private ConcurrentHashMap<String,List<Role>> authoritiesmap = new ConcurrentHashMap<>();
    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    private UserMapper userMapper;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String loginName = authentication.getName();
        String password = (String)authentication.getCredentials();
        //校验用户名密码
        User user = userMapper.queryByUsername(loginName);
        if(user == null || !checkPassWord(password,user.getPasswrd())){
            throw new BadCredentialsException("没有权限");
        }
        //授权
        return new UsernamePasswordAuthenticationToken(loginName,password,user.getAuthorities());
    }

    private boolean checkPassWord(String password,String target){
        PasswordEncoder passwordEncoder =
                PasswordEncoderFactories.createDelegatingPasswordEncoder();
        return passwordEncoder.matches(password,target);
    }
}
